import {createRouter,createWebHistory} from "vue-router";
import Index from "../pages/Index.vue";
import Login from "../pages/Login.vue";

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import Welcome from "../pages/Welcome.vue";
import UserList from "../pages/user/UserList.vue";
import PayList from "../pages/pay/PayList.vue";

NProgress.configure({ showSpinner: false })

const routes = [
    {
        path:'/index',
        name:'index',
        component:Index,
        children:[
            {
                path:'/index',
                name:'welcome',
                component: Welcome
            },
            {
                path:'/userlist',
                name:'userlist',
                component: UserList
            },
            {
                path:'/paylist',
                name:'paylist',
                component: PayList
            },

        ]
    },
    {
        path:'/login',
        name:'login',
        component:Login
    },
    {
        path:'/',
        redirect:'/index'
    },
]

const router = createRouter({
    history:createWebHistory(),
    routes
})

// 前置守卫
router.beforeEach((to,from,next)=>{
    console.log("前置守卫")
    NProgress.start();
    let token = sessionStorage.getItem("token");
    if(to.name == 'login'){
        next();
    }else{
        if(!token){
            // 没有token 应该跳转到login页面
            next({
                name:'login'
            })
        }else{
            next();
        }
    }
})

// 后置守卫
router.afterEach((to,from)=>{
    console.log("后置守卫")
    NProgress.done()
})

export default router